//
//  XPUserAccount.swift
//  SinaWeibo
//
//  Created by 徐攀 on 16/5/12.
//  Copyright © 2016年 徐攀. All rights reserved.
//

import UIKit

class XPUserAccount: NSObject, NSCoding {
    // MARK: -需要的所有账户信息
    // 授权码
    var access_token: String?
    // 授权码的可用生命周期
    var expires_in: NSTimeInterval = 0 {
        didSet {
            expiresTime = NSDate().dateByAddingTimeInterval(expires_in)
        }
    }
    // 授权码失效的时间(当前时间+生命周期)
    var expiresTime: NSDate?
    // 用户唯一标识
    var uid: Int64 = 0
    // 用户昵称
    var name: String?
    // 用户头像
    var avatar_large: String?
    
    // MARK: -字典转模型
    init(dict: [String: AnyObject]) {
        super.init()
        setValuesForKeysWithDictionary(dict)
    }
    override func setValue(value: AnyObject?, forUndefinedKey key: String) {}
    
    override var description: String {
        let keys = ["access_token", "expires_in", "uid", "name", "avatar_large"]
        return dictionaryWithValuesForKeys(keys).description
    }
    
    // MARK: -解档(记得解档出来给属性赋值)
    required init?(coder aDecoder: NSCoder) {
        access_token = aDecoder.decodeObjectForKey("access_token") as? String
        expiresTime = aDecoder.decodeObjectForKey("expiresTime") as? NSDate
        name = aDecoder.decodeObjectForKey("name") as? String
        avatar_large = aDecoder.decodeObjectForKey("avatar_large") as? String
        uid = aDecoder.decodeInt64ForKey("uid")
    }
    // MARK: -归档
    func encodeWithCoder(aCoder: NSCoder) {
        aCoder.encodeInt64(uid, forKey: "uid")
        aCoder.encodeObject(access_token, forKey: "access_token")
        aCoder.encodeObject(expiresTime, forKey: "expiresTime")
        aCoder.encodeObject(name, forKey: "name")
        aCoder.encodeObject(avatar_large, forKey: "avatar_large")
    }
}
// MARK: - 供外界归档/解档调用的方法
extension XPUserAccount {
    // 归档
    func saveUserInfo() -> Bool {
        let path = (NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true).last! as NSString).stringByAppendingPathComponent("userInfo.archiver")
        print(path)
        return NSKeyedArchiver.archiveRootObject(self, toFile: path)
    }
    // 解档
    class func loadUserInfo() -> XPUserAccount? {
        let path = (NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true).last! as NSString).stringByAppendingPathComponent("userInfo.archiver")
        return NSKeyedUnarchiver.unarchiveObjectWithFile(path) as? XPUserAccount
    }
}




